#include "stdafx.h"
#include "UploadUrlBox.h"

using namespace ui;

void UrlInputElement::Init() 
{
	__super::Init();
	m_pReUrl = static_cast<RichEdit*>(FindSubControl(L"re_url"));
	m_pReFileName = static_cast<RichEdit*>(FindSubControl(L"re_filename"));
	m_pBtnClear = static_cast<Button*>(FindSubControl(L"btn_clear"));
}
void UrlInputElement::Clear() 
{
	if (!IsInited())
		return;
	m_pReUrl->SetText(L"");
	m_pReFileName->SetText(L"");
}

std::string UrlInputElement::GetUrl() const 
{
	return m_pReUrl ? m_pReUrl->GetUTF8Text() : "";
}
std::string UrlInputElement::GetFileName() const 
{
	return m_pReFileName ? m_pReFileName->GetUTF8Text() : "";
}
bool UrlInputElement::IsElementValue() 
{
	if (!m_pReUrl)
		return false;
	std::string url = m_pReUrl->GetUTF8Text();
	nbase::StringTrim(url);
	return url.empty();
}

	UploadUrlBox::UploadUrlBox() :ListBox(new ui::VLayout()) {
		
	};
	UploadUrlBox::~UploadUrlBox() {
		
	}

	void UploadUrlBox::Init() {
		__super::Init();
		ListContainerElement* ele = new ListContainerElement;
		GlobalManager::FillBoxWithCache(ele, L"sdp/upload_parse_file_form/url_input_element_add.xml");
		Button* btnAdd = (Button*)ele->FindSubControl(L"add");
		btnAdd->AttachClick(nbase::Bind(&UploadUrlBox::OnListItemAddClicked, this, std::placeholders::_1));
		Add(ele);
		InsertUrlInputElement();
	}

	UrlInputElement* UploadUrlBox::CreateUrlInputElement(std::wstring sXml) {
		UrlInputElement* ele = new UrlInputElement();
		GlobalManager::FillBoxWithCache(ele, sXml);
		Button* btnClear = (Button*)ele->FindSubControl(L"btn_clear");
		btnClear->AttachClick(nbase::Bind(&UploadUrlBox::OnListItemClearClicked, this, std::placeholders::_1, ele));
		return ele;
	}

	bool UploadUrlBox::InsertUrlInputElement() {
		UrlInputElement* ele = CreateUrlInputElement(L"sdp/upload_parse_file_form/url_input_element.xml");
		int index = GetCount() - 1;
		assert(index >= 0);
		if (index % 2 == 1)
			ele->SetBkColor(L"bk_listitem_hovered");
		return AddAt(ele, index);
	}

	bool UploadUrlBox::ClearUrlInputElement(UrlInputElement* ele) {
		if (!ele)
			return false;
		ele->Clear();
		return true;
	}
	bool UploadUrlBox::ClearAllUrlInputElement() {
		int count = GetCount();
		for (int i = 0; i < count - 1; i++)
		{
			UrlInputElement* ele = dynamic_cast<UrlInputElement*>(GetItemAt(i));
			if (ele)
				ele->Clear();
		}
		return true;
	}

	bool UploadUrlBox::OnListItemClearClicked(ui::EventArgs* args, UrlInputElement* ele) {
		ClearUrlInputElement(ele);
		return true;
	}

	bool UploadUrlBox::OnListItemAddClicked(ui::EventArgs* args)
	{
		InsertUrlInputElement();
		return true;
	}






